package com.bigfans.framework.jms;

import javax.jms.Message;
import javax.jms.MessageListener;
import javax.jms.TextMessage;
import java.lang.reflect.Method;

public class MethodMessageListener implements MessageListener {

    private MessageReceiver messageReceiver;
    private Method method;

    public MethodMessageListener(MessageReceiver messageReceiver, Method method) {
        this.messageReceiver = messageReceiver;
        this.method = method;
    }

    public void onMessage(Message message) {
        Class<?>[] parameterTypes = method.getParameterTypes();
        Class<?> paramClass = parameterTypes[0];
        try {
            if (paramClass.equals(String.class)) {
                TextMessage tm = (TextMessage) message;
                method.invoke(this.messageReceiver, tm.getText());
            } else if (paramClass.equals(Message.class)) {
                method.invoke(this.messageReceiver, message);
            } else {
                method.invoke(this.messageReceiver, message.getBody(paramClass));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
